package com.fairchild.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

public class PropertyConfigUtil extends PropertyPlaceholderConfigurer {
	
	private final static HashMap<String, String> PROP_MAP = new HashMap<String, String> ();
	private static String[] encryptPropNames;
	
	static {
		encryptPropNames = getPropValue("encrypField", "db.properties").split(",");
	}
	
	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
		super.processProperties(beanFactoryToProcess, props);
		for (Object key : props.keySet()) {
			String keyStr = key.toString();
			String value = props.getProperty(keyStr);
			PROP_MAP.put(keyStr, value);
		}
	}
	
	@Override
	protected String convertProperty(String propertyName, String propertyValue) {	
		if (isEncryptProp(propertyName)) {
			String decryptValue = DesUtil.getDecryptString(propertyValue);
			return decryptValue;
		} else {
			return propertyValue;
		}
	}
	
	public static String getContextProperty(String name) {
		String str = PROP_MAP.get(name);
		if (str == null) {
			str = "";
		}
		return str;
	}
	
	private boolean isEncryptProp(String propertyName){
		for(String encryptPropName:encryptPropNames){
			if(encryptPropName.equals(propertyName)){
				return true;
			}
		}
		return false;
	}
	
	private static String getPropValue(String keyName, String filePath){
		Resource resource = new ClassPathResource(filePath);
		Properties prop = new Properties();
		InputStream in = null;
		try {
			in = resource.getInputStream();
			prop.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return prop.getProperty(keyName);
	}

}
